<template>
  <VPage class="app-container">
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <el-input v-model="form.back_purchase_order_no" placeholder="采购单号" class="w-40"></el-input>
        <el-input v-model="form.back_warehouse_order_no" placeholder="退货单号" class="w-40"></el-input>
        <el-input v-model="form.sku" placeholder="SKU" class="w-40"></el-input>
        <select-personnel class="w-40" v-model="form.create_user_id" placeholder="创建人"></select-personnel>
        <el-select class="selectClass" v-model="form.back_type" placeholder="退货类型" multiple collapse-tags>
          <el-option v-for="item in options['back.backDeliveryOrder']?.[0].backDeliveryOrderType" :key="item.value"
            :label="item.label" :value="item.value"></el-option>
        </el-select>
        <el-select class="selectClass w-30" v-model="form.handle_status" placeholder="处理状态" multiple>
          <el-option v-for="item in options['back.backDeliveryOrder']?.[0].backDeliveryOrderHandleStatus"
            :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <VGroup>
          <el-select class="selectClass" v-model="form.timeRange.type" style="max-width: 100px">
            <el-option v-for="item in timeOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <el-date-picker v-model="form.timeRange.value" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" :default-time="defaultTime()"
            style="max-width: 300px" />
        </VGroup>

      </template>
      <template #toolbar_btns>
        <div class="flex justify-between w-full">
          <el-button @click="handleDeal()">批量处理</el-button>
          <el-button class="ml-auto" @click="handleExport"><svg-icon icon-class="import" />导出</el-button>
        </div>
      </template>
    </VTable>
    <ComModal ref="ComModalRef" @query="query"></ComModal>
    <derived-center ref="DerivedCenterRef"></derived-center>

  </VPage>
</template>
<script setup name="ReturnBack-delivery" lang="jsx">
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, toRefs } from 'vue'
import { getEnums } from '@/api/public'
import { queryBackDeliveryList, handleBackDelivery } from './api'
import { getWareData } from '@/api/public'
import ComModal from './components/ComModal.vue'

const timeOption = [
  { label: "创建时间", value: "create_time" },
  { label: "处理时间", value: "handle_time" },
]

const tableRef = ref()
const tableOptins = reactive({
  rowConfig: { height: 60 },
  formConfig: {
    data: {
      timeRange: { type: 'create_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: "40" },
    {
      type: "seq", title: '序号', width: 80
    },
    {
      field: 'back_purchase_order_no', title: '采购单号', width: 180
    },
    {
      field: 'back_warehouse_order_no', title: '退货单号', width: 180, slots: {
        default: ({ row }) => {
          return <div class="base-text-color cursor-pointer" onClick={() => open('view', row.id)}> {row.back_warehouse_order_no} </div>
        }
      }
    },
    {
      field: 'warehouse_name', title: '仓库', width: 120
    },
    {
      field: 'back_type_cn', title: '退货类型', width: 120
    },
    {
      field: 'back_type_cn', title: '退货方式', width: 120, slots: {
        default: ({ row }) => {
          return <div>{row.join?.back_mode_cn}</div>
        }
      }
    },
    {
      field: 'handle_status_cn', title: '退货状态', width: 100
    },
    {
      field: 'create_user', title: '创建人', width: 160
    },
    {
      field: 'create_time', title: '创建日期', width: 180
    },
    {
      field: 'handle_user', title: '处理人', width: 160
    },
    {
      field: 'handle_time', title: '处理时间', width: 180
    },
    {
      field: 'remark', title: '备注', width: 120
    },
    {
      title: '操作', width: "65", fixed: "right", slots: {
        default: ({ row }) => {
          return <div class="table-option">
            <div>
              {row.handle_status == 0 && <el-link type="primary" underline={false} class="mr-2" onClick={() => handleDeal(row.id)}>处理</el-link>}
              {row.handle_status != 1 && <el-link type="primary" underline={false} class="mr-2" onClick={() => open('edit', row.id)}>编辑</el-link>}
            </div>
          </div >
        }
      }
    }
  ],
  proxyConfig: {
    seq: true,
    props: {
      result: 'data',
      total: 'total',
    },
    ajax: {
      query: async ({ page, form }) => {
        const res = await queryBackDeliveryList({ ...form, ...page })
        return new Promise(function (resolve) {
          resolve({
            data: res.data,
            total: res.total
          })
        })
      }
    }
  }
})
const query = () => {
  tableRef.value.query()
}

const data = reactive({
  options: [],
  wareDataList: [],
  floorList: [],
  areaList: []
})
const { options, wareDataList, floorList, areaList } = toRefs(data)

// 获取枚举类
const fetchOption = async () => {
  getEnums({
    version: "v1", "name": [
      "back.backDeliveryOrder"
    ]
  }).then(res => {
    options.value = res.data
  })
}
provide('options', options)
fetchOption()

// 获取仓库
const getWareDataList = async () => {
  try {
    const res = await getWareData()
    wareDataList.value = res.data
  } catch (e) {
    throw Error(e)
  }
}
provide('wareDataList', wareDataList)
getWareDataList()


const changeWarehouse = async (val) => {
  console.log(val)
  let floors = []
  wareDataList.value.forEach(element => {
    if (val && val.includes(element.id)) {
      floors.push(...element.floors)
    }
  });
  floorList.value = floors
  areaList.value = []
  tableRef?.value.setFormField('floor_id', '')
  tableRef?.value.setFormField('area_id', '')
}

const changeFloor = async (val) => {
  let areas = []
  floorList.value.forEach(element => {
    if (val && val.includes(element.id)) {
      areas.push(...element.areas)
    }
  });
  areaList.value = areas
  tableRef?.value.setFormField('area_id', '')
}

const ComModalRef = ref()
const open = (type, id) => {
  ComModalRef.value.open(type, id)
}

// 批量确认
const handleDeal = (id) => {
  const records = getSelectRow().map(i => {
    return i.id
  })
  if (!id) {
    if (records.length == 0) {
      ElMessage.error('请先选择行')
      return
    }
  }
  const ids = id ? [id] : records
  ElMessageBox.confirm('是否处理当前项?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    handleBackDelivery({ ids })
      .then((res) => {
        query()
        ElMessage.success(res.message)
      })
  })
}

// 导出
const DerivedCenterRef = ref()
const handleExport = (val) => {
  let condition = tableRef.value.getQueryForm()
  DerivedCenterRef.value.open({
    id: 53,
    tag_name: 'wms',
    condition
  })
}
//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords()
}

</script>